document.addEventListener('DOMContentLoaded', function() {
    // Toggle Favorites
    const toggleFavoriteButtons = document.querySelectorAll('.toggle-favorite, .add-to-favorites');
    toggleFavoriteButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const carId = this.dataset.carId;
            
            fetch('toggle_favorite.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `car_id=${carId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.action === 'added') {
                        this.classList.remove('btn-outline-danger');
                        this.classList.add('btn-danger');
                        if (this.textContent) {
                            this.innerHTML = '<i class="fas fa-heart"></i> Remove from Favorites';
                        }
                    } else {
                        this.classList.add('btn-outline-danger');
                        this.classList.remove('btn-danger');
                        if (this.textContent) {
                            this.innerHTML = '<i class="fas fa-heart"></i> Add to Favorites';
                        }
                    }
                }
            })
            .catch(error => console.error('Error:', error));
        });
    });

    // Handle car comparison
    const compareButtons = document.querySelectorAll('.add-to-compare');
    const compareCounter = document.getElementById('compare-counter');
    let carsToCompare = [];

    compareButtons.forEach(button => {
        button.addEventListener('click', function() {
            const carId = this.dataset.carId;
            
            if (this.classList.contains('active')) {
                // Remove from comparison
                carsToCompare = carsToCompare.filter(id => id !== carId);
                this.classList.remove('active');
                this.innerHTML = '<i class="fas fa-balance-scale"></i> Compare';
            } else {
                // Add to comparison
                if (carsToCompare.length >= 3) {
                    alert('You can compare up to 3 cars at a time');
                    return;
                }
                carsToCompare.push(carId);
                this.classList.add('active');
                this.innerHTML = '<i class="fas fa-check"></i> Added to Compare';
            }

            // Update counter and comparison button
            compareCounter.textContent = carsToCompare.length;
            document.getElementById('compare-cars-btn').style.display = 
                carsToCompare.length >= 2 ? 'block' : 'none';
        });
    });

    // Handle compare button click
    document.getElementById('compare-cars-btn')?.addEventListener('click', function() {
        if (carsToCompare.length >= 2) {
            window.location.href = `compare.php?cars=${carsToCompare.join(',')}`;
        }
    });

    // Handle dynamic brand-model relationship
    const brandSelect = document.getElementById('brand-select');
    const modelSelect = document.getElementById('model-select');

    if (brandSelect && modelSelect) {
        brandSelect.addEventListener('change', function() {
            const brandId = this.value;
            
            if (brandId) {
                // Enable model select
                modelSelect.disabled = false;
                
                // Fetch models for selected brand
                fetch(`get_models.php?brand_id=${brandId}`)
                    .then(response => response.json())
                    .then(models => {
                        // Clear current options
                        modelSelect.innerHTML = '<option value="">Select Model</option>';
                        
                        // Add new options
                        models.forEach(model => {
                            const option = document.createElement('option');
                            option.value = model.id;
                            option.textContent = model.name;
                            modelSelect.appendChild(option);
                        });
                    })
                    .catch(error => console.error('Error:', error));
            } else {
                // Disable and reset model select
                modelSelect.disabled = true;
                modelSelect.innerHTML = '<option value="">Select Brand First</option>';
            }
        });
    }
}); 